package com.bw.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.bw.dao.ProductReplyMapper;
import com.bw.entity.PageResult;
import com.bw.pojo.comment.ItemProductPages;
import com.bw.pojo.comment.ProductReply;
import com.bw.pojo.comment.ProductReplyPages;
import com.bw.pojo.goods.Sku;
import com.bw.pojo.goods.Spu;
import com.bw.pojo.order.Order;
import com.bw.pojo.order.OrderItem;
import com.bw.pojo.user.User;
import com.bw.service.comment.ProductReplyService;
import com.bw.service.goods.SkuService;
import com.bw.service.goods.SpuService;
import com.bw.service.order.OrderItemService;
import com.bw.service.order.OrderService;
import com.bw.service.user.UserService;
import com.bw.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = ProductReplyService.class)
public class ProductReplyServiceImpl implements ProductReplyService {

    @Autowired
    private ProductReplyMapper productReplyMapper;
    @Reference
    private SkuService skuService;
    @Reference
    private SpuService spuService;
    @Reference
    private OrderService orderService;
    @Autowired
    private IdWorker idWorker;
    @Reference
    private UserService userService;
    @Reference
    private OrderItemService orderItemService;

    @Override
    public ProductReplyPages findHasReplyPageBySkuId(int page, int size, String skuId) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        criteria.andIsNotNull("replyContent");
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public ProductReplyPages findGoodCommentPageBySkuId(int page, int size, String skuId) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        criteria.andGreaterThanOrEqualTo("productScore",4);
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public ProductReply findByOrderId(String orderId){
        System.out.println(orderId);
        Example example =new Example(ProductReply.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        List<ProductReply> productReply=  productReplyMapper.selectByExample(example);
        System.out.println(productReply.size());
        return productReply.get(0);
    }

    @Override
    public ProductReplyPages findMiddleCommentPageBySkuId(int page, int size, String skuId) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        criteria.andBetween("productScore",2,4);
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public ProductReplyPages findBadCommentPageBySkuId(int page, int size, String skuId) {

        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        criteria.andLessThan("productScore",2);
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public ProductReplyPages findHasPicPageBySkuId(int page, int size, String skuId) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        criteria.andIsNotNull("replyImage");
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public Integer[] getCommentCount(String skuId) {
        Integer[] commentCount= new Integer[6];
        commentCount[0] = productReplyMapper.getAllCommentsCount(skuId);
        commentCount[1] = productReplyMapper.getHasPictureCommentsCount(skuId);
        commentCount[2] = productReplyMapper.getHasFollowCommentsCount(skuId);
        commentCount[3] = productReplyMapper.getGoodCommentsCount(skuId);
        commentCount[4] = productReplyMapper.getMiddleCommentsCount(skuId);
        commentCount[5] = productReplyMapper.getBadCommentsCount(skuId);
        return commentCount;
    }

    private ProductReplyPages findPageByExample(int page, int size,String skuId,Example example){
        PageHelper.startPage(page,size);
        List<ProductReply> productReplies1 = productReplyMapper.selectByExample(example);
        PageInfo<ProductReply> productReplyPageInfo = new PageInfo<ProductReply>(productReplies1);
        List<ProductReply> rows = productReplyPageInfo.getList();
        for (ProductReply row : rows) {
            StringBuilder replace= new StringBuilder(" ");
            replace.append(" ");
            Map specItems = JSON.parseObject(row.getSpec());
            for (Object value : specItems.values()) {
                replace.append((String) value).append(" ");
            }
            String image = row.getReplyImage();
            if(image==null) {
//                row.setReplyImage("");
                row.setSpec(replace.toString());
                continue;}
            String[] split = image.split(",");
            row.setReplyImage(split[0]);
            row.setSpec(replace.toString());
        }
        ProductReplyPages productReplyPages = new ProductReplyPages();
        Double satisfaction = productReplyMapper.Satisfaction(skuId);
        productReplyPages.setProductReplyPageInfo(productReplyPageInfo);
        productReplyPages.setSatisfaction(satisfaction);
        return productReplyPages;
    }

    @Override
    public PageResult<ItemProductPages> findItemPage(int page, int size,String username) {
        PageHelper.startPage(page,size);
        List<ItemProductPages> items = productReplyMapper.getOrderId(username);
        for (ItemProductPages item : items) {
            System.out.println("***********"+item.getId());
//            选取评论
            Example example = new Example(ProductReply.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId",item.getId());
            List<ProductReply> productReplies = productReplyMapper.selectByExample(example);

            try {
                item.setList(productReplies.get(0));
//            选择商品
                item.setCmm(orderItemService.findByOrderId(item.getId()));
            } catch (Exception e) {
                e.printStackTrace();
//                continue;
//
            }
        }
//        PageHelper.startPage(page,size);
        Page<ItemProductPages> itemProductPages = (Page<ItemProductPages>)  items;
        return new PageResult<>(itemProductPages.getTotal(), itemProductPages.getResult());
//        return null;
    }

    /**
     *
     * @param page 页码
     * @param size 每页记录数
     * @param skuId sku的id
     * @return
     */
    @Override
    public ProductReplyPages findAllPageBySkuId(int page, int size, String skuId) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("skuId",skuId);
        return findPageByExample(page,size,skuId,example);
    }

    @Override
    public PageResult<ProductReply> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete",0);
        Page<ProductReply> productReplyPage = (Page<ProductReply>) productReplyMapper.selectByExample(example);
        return new PageResult<>(productReplyPage.getTotal(), productReplyPage.getResult());
    }
    @Override
    public PageResult<ProductReply> findBinPage(int page, int size) {
        PageHelper.startPage(page,size);
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete",1);
        Page<ProductReply> productReplyPage = (Page<ProductReply>) productReplyMapper.selectByExample(example);
        return new PageResult<>(productReplyPage.getTotal(), productReplyPage.getResult());
    }

    /**
     * 分页+查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<ProductReply> findPageSearch(Map<String, Object> searchMap, int page, int size) {
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName",searchMap.get("userName"));
        PageHelper.startPage(page,size);
        Page<ProductReply> productReplies = (Page<ProductReply>) productReplyMapper.selectByExample(example);
        return new PageResult<>(productReplies.getTotal(), productReplies.getResult());
    }

    /**
     * 根据评论的id查询评论
     * @param id
     * @return
     */
    @Override
    public ProductReply findById(String id) {
        return productReplyMapper.selectByPrimaryKey(id);
    }

    /**
     * 管理员查看所有人的评论
     * @return
     */
    public List<ProductReply> findAll(){return productReplyMapper.selectAll();}

    /**
     * 删除评论
     * @param id
     */
    public void delete(String id){
        ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
        productReply.setIsDelete("1");//删除
        productReplyMapper.updateByPrimaryKeySelective(productReply);
    }

    /**
     * 还原评论
     * @param id
     */
    public void restore(String id){
        ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
        productReply.setIsDelete("0");//恢复状态
        productReplyMapper.updateByPrimaryKeySelective(productReply);
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Transactional
    public void deleMany(String[] ids) {
        for (String id: ids) {
            ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
            productReply.setIsDelete("1");
            productReplyMapper.updateByPrimaryKeySelective(productReply);

        }
    }
    /**
     * 批量还原
     * @param ids
     * @return
     */
    @Transactional
    public void resMany(String[] ids) {
        for (String id: ids) {
            ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
            productReply.setIsDelete("0");
            productReplyMapper.updateByPrimaryKeySelective(productReply);

        }
    }

    @Override
    public void update(ProductReply productReply) {
        productReplyMapper.updateByPrimaryKeySelective(productReply);
    }

    /**
     *模糊查询+分页
     * @param searchMap
     * @return
     */
    @Override
    public PageResult<ProductReply> findPage(Map<String, Object> searchMap,int page, int size) {
        PageHelper.startPage(page,size);
        System.out.println(searchMap.get("skuName"));
        System.out.println(searchMap.get("replyContent"));
        System.out.println(searchMap.get("productType"));
        System.out.println(searchMap.get("userName"));
        Example example = createExample(searchMap);
        Page<ProductReply> productReplies=(Page<ProductReply>)productReplyMapper.selectByExample(example);
        return new PageResult<ProductReply>(productReplies.getTotal(),productReplies.getResult());
    }


    /**
     * 根据商品id数组查询商品
     */
    public List<Sku> findSkuListBySkuIds(Map<String, Object> searchMap) {
        return skuService.findList(searchMap);
    }


    /**
     * 添加第一次的评论
     */
    public void add(String orderId,String skuId){
        ProductReply productReply=new ProductReply();
        Order order=orderService.findById(orderId);
        Sku sku=skuService.findById(skuId);
        String spuId=sku.getSpuId();
        Spu spu=spuService.findById(spuId);
        String username=order.getUsername();
        User user=userService.findById(username);
        String headPic=user.getHeadPic();


        productReply.setId(idWorker.nextId()+"");
        productReply.setOrderId(order.getId());
        productReply.setSkuId(skuId);
        productReply.setSkuName(sku.getName());
        productReply.setSkuUniqueId(spuId);
        productReply.setSpuName(spu.getName());
        productReply.setUserName(username);
        productReply.setUserHeadPic(headPic);

        //待改动
        productReply.setProductType("0");
        productReply.setProductScore(5);//商品分数
        productReply.setServiceScore(5);//服务分数
        productReply.setExpressScore(5);//物流分数
        productReply.setReplyContent("测试用");//评论内容

        //以下不用改动
        productReply.setIsDelete("0");//是否删除，默认0
        productReply.setIsReply("0");//是否回复，默认0
        productReply.setBrowses(0);//浏览数，从0开始
        productReply.setLikes(0);//点赞数，从0开始
        productReply.setCreateTime(new Date());//创建时间
        productReplyMapper.insert(productReply);

    }
    public void add1(ProductReply productReply){
        Order order=orderService.findById(productReply.getOrderId());
        Sku sku=skuService.findById(productReply.getSkuId());

        Spu spu=spuService.findById(sku.getSpuId());
        String username=order.getUsername();
        System.out.println(username);
        User user=userService.findById(username);
        String headPic=user.getHeadPic();


        productReply.setId(idWorker.nextId()+"");
        productReply.setSkuName(sku.getName());
        productReply.setSkuUniqueId(sku.getSpuId());
        productReply.setSpuName(spu.getName());
        productReply.setUserName(username);
        productReply.setUserHeadPic(headPic);

        //待改动
        productReply.setProductType("0");
        productReply.setSpec(sku.getSpec());

        //以下不用改动
        productReply.setIsDelete("0");//是否删除，默认0
        productReply.setIsReply("0");//是否回复，默认0
        productReply.setBrowses(0);//浏览数，从0开始
        productReply.setLikes(0);//点赞数，从0开始
        productReply.setCreateTime(new Date());//创建时间


        //插入
//        order.setOrderStatus("5");
        order.setBuyerRate("1");
        orderService.update(order);
        productReplyMapper.insert(productReply);
    }



    /**
     * 超时自动好评
     */
    public void TimeOut(){

//        Example example = new Example(Order.class);
//        Example.Criteria criteria = example.createCriteria();
//        //criteria.andLessThan("createTime",localDateTime);//创建时间小于超时时间
//        criteria.andEqualTo("orderStatus","4");//条件是未评论的订单
//        criteria.andEqualTo("isDelete","0");//未删除的订单
//
//        List<Order> orders=orderService.orderList(example);


        Sku sku =skuService.findById(productReplyMapper.skuid());
        Spu spu =spuService.findById(productReplyMapper.spuid());
        Order order=orderService.findById(productReplyMapper.orderid());
        String username=order.getUsername();
        User user=userService.findById(username);
        String headPic=user.getHeadPic();
        ProductReply productReply=new ProductReply();
        productReply.setId(idWorker.nextId()+"");
        productReply.setOrderId(productReplyMapper.orderid());
        productReply.setSkuId(sku.getId());
        productReply.setSkuName(sku.getName());
        productReply.setSkuUniqueId(productReplyMapper.spuid());
        productReply.setSpuName(spu.getName());
        productReply.setUserName(username);
        productReply.setUserHeadPic(headPic);

        //待改动
        productReply.setProductType("0");
        productReply.setProductScore(5);//商品分数
        productReply.setServiceScore(5);//服务分数
        productReply.setExpressScore(5);//物流分数
        productReply.setReplyContent("该用户超时未评论，系统将默认好评");//评论内容

        //以下不用改动
        productReply.setIsDelete("0");//是否删除，默认0
        productReply.setIsReply("0");//是否回复，默认0
        productReply.setBrowses(0);//浏览数，从0开始
        productReply.setLikes(0);//点赞数，从0开始
        productReply.setCreateTime(new Date());//创建时间

        productReplyMapper.insert(productReply);

    }



    /**
     * 追评
     */
    public void follow(String id,String content,String image){
        ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
        productReply.setFollowContent(content);
        productReply.setFollowImage(image);
        productReply.setUpdateTime(new Date());
        productReplyMapper.updateByPrimaryKeySelective(productReply);
    }
    /**
     * 删除追评
     */
    public void deleteFollow(String id){
        productReplyMapper.deleteFollow(id);
    }

    /**
     * 添加虚拟评论
     */
    public void addVirtual(List<ProductReply> productReplies){
        System.out.println(productReplies);
        for (ProductReply productReply : productReplies) {
            System.out.println(productReplies);
            productReply.setId(idWorker.nextId()+"");
            productReply.setSkuId(skuService.findByName(productReply.getSkuName()).getId());
            productReply.setSkuUniqueId(skuService.findById(productReply.getSkuId()).getSpuId());
            productReply.setSpuName(spuService.findById(skuService.findById(productReply.getSkuId()).getSpuId()).getName());
            productReply.setProductType("0");
            productReply.setProductScore(5);//商品分数
            productReply.setServiceScore(5);//服务分数
            productReply.setExpressScore(5);//物流分数
            productReply.setIsDelete("0");//是否删除，默认0
            productReply.setIsReply("0");//是否回复，默认0
            productReply.setBrowses(0);//浏览数，从0开始
            productReply.setLikes(0);//点赞数，从0开始
            productReply.setCreateTime(new Date());//创建时间
            productReply.setSpec("{}");//点赞数，从0开始
            productReplyMapper.insert(productReply);

        }
//        ProductReply productReply=new ProductReply();
//        Sku sku=skuService.findById(skuId);
//        String spuId=sku.getSpuId();
//        Spu spu=spuService.findById(spuId);


//        productReply.setId(idWorker.nextId()+"");
//        productReply.setSkuId(skuId);
//        productReply.setSkuName(sku.getName());
//        productReply.setSkuUniqueId(spuId);
//        productReply.setSpuName(spu.getName());

//        switch (type) {
//            case 1:
//                productReply.setReplyContent("虚拟评论一个");//评论内容
//            case 2:
//                productReply.setReplyContent("东西质量非常好，与卖家描述的完全一致，非常满意,真的很喜欢，完全超出期望值，发货速度非常快，包装非常仔细、严实，物流公司服务态度很好，运送速度很快，很满意的一次购物。");//评论内容
//            case 3:
//                productReply.setReplyContent("终于收到我需要的宝贝了，东西很好，价美物廉，谢谢掌柜的！说实在，这是我淘宝购物来让我最满意的一次购物。无论是掌柜的态度还是对物品，我都非常满意的。掌柜态度很专业热情，有问必答，回复也很快，我问了不少问题，他都不觉得烦，都会认真回答我，这点我向掌柜表示由衷的敬意，这样的好掌柜可不多。再说宝贝，正是我需要的，收到的时候包装完整，打开后让我惊喜的是，宝贝比我想象中的还要好！不得不得竖起大拇指。下次需要的时候我还会再来的，到时候麻烦掌柜给个优惠哦！");
//            case 4:
//                productReply.setReplyContent("收到货，第一时间拆包装，感觉质量还是比较好的，与卖家描述的还是一致的，非常满意，发货速度比较快，物流公司服务态度很好，运送速度很快，总的来说这次是很满意的一次购物，感谢卖家。");
//            case 5:
//                productReply.setReplyContent("物流超级给力很快就收到货啦，卖家老板特别好建议的尺码非常合适，衣服做工精致!面料质地厚实，颜色好看，质量真的非常好!版型设计非常好看，穿上显气质!超级满意!好评!");
//        }
        //以下不用改动

    }








    /**
     * 管理员的分页查询
     */
    @Override
    public PageResult<ProductReply> findListPage(int page, int size) {
        PageHelper.startPage(page,size);
        Example example = new Example(ProductReply.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDelete",0);
        Page<ProductReply> productReplyPage = (Page<ProductReply>) productReplyMapper.selectByExample(example);
        return new PageResult<>(productReplyPage.getTotal(), productReplyPage.getResult());

    }

    /**
     * 阅读量+1
     * @param id
     */
    @Override
    public void browsesAdd(String id){
        ProductReply productReply=productReplyMapper.selectByPrimaryKey(id);
        productReply.setBrowses(productReply.getBrowses()+1);
        productReplyMapper.updateByPrimaryKeySelective(productReply);
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String,Object> searchMap){
        Example example=new Example(ProductReply.class);
        Example.Criteria criteria=example.createCriteria();
        if(searchMap!=null){
            //评论id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
            }
            //订单id
            if(searchMap.get("orderId")!=null && !"".equals(searchMap.get("orderId"))){
                criteria.andEqualTo("orderId",searchMap.get("orderId"));
            }
            //skuid
            if(searchMap.get("skuId")!=null && !"".equals(searchMap.get("skuId"))){
                criteria.andLike("skuId","%"+searchMap.get("skuId")+"%");
            }
            //sku_unique_id,实际上就是spuid
            if(searchMap.get("skuUniqueId")!=null && !"".equals(searchMap.get("skuUniqueId"))){
                criteria.andLike("skuUniqueId","%"+searchMap.get("skuUniqueId")+"%");
            }
            //商品类型，0普通商品，1秒杀商品
            if(searchMap.get("productType")!=null && !"".equals(searchMap.get("productType"))){
                criteria.andLike("productType","%"+searchMap.get("productType")+"%");
            }
            //评论图片
            if(searchMap.get("replyImage")!=null && !"".equals(searchMap.get("replyImage"))){
                criteria.andLike("replyImage","%"+searchMap.get("replyImage")+"%");
            }
            //评论内容
            if(searchMap.get("replyContent")!=null && !"".equals(searchMap.get("replyContent"))){
                criteria.andLike("replyContent","%"+searchMap.get("replyContent")+"%");
            }
            //追评图片
            if(searchMap.get("followImage")!=null && !"".equals(searchMap.get("followImage"))){
                criteria.andLike("followImage","%"+searchMap.get("followImage")+"%");
            }
            //追评内容
            if(searchMap.get("followContent")!=null && !"".equals(searchMap.get("followContent"))){
                criteria.andLike("followContent","%"+searchMap.get("followContent")+"%");
            }
            //是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
            //商家是否回复
            if(searchMap.get("isReply")!=null && !"".equals(searchMap.get("isReply"))){
                criteria.andLike("isReply","%"+searchMap.get("isReply")+"%");
            }
            //浏览量
            if(searchMap.get("browses")!=null && !"".equals(searchMap.get("browses"))){
                criteria.andLike("browses","%"+searchMap.get("browses")+"%");
            }
            //点赞数
            if(searchMap.get("likes")!=null && !"".equals(searchMap.get("likes"))){
                criteria.andLike("likes","%"+searchMap.get("likes")+"%");
            }
            //用户名
            if(searchMap.get("userName")!=null && !"".equals(searchMap.get("userName"))){
                criteria.andLike("userName","%"+searchMap.get("userName")+"%");
            }
            //头像
            if(searchMap.get("userHeadPic")!=null && !"".equals(searchMap.get("userHeadPic"))){
                criteria.andLike("userHeadPic","%"+searchMap.get("userHeadPic")+"%");
            }
            if(searchMap.get("spec")!=null&&!"".equals(searchMap.get("spec"))){
                criteria.andLike("spec","%"+searchMap.get("spec")+"%");
            }

            //商品分数
            if(searchMap.get("productScore")!=null){
                criteria.andEqualTo("productScore",searchMap.get("productScore"));
            }
            //服务分数
            if(searchMap.get("serviceScore")!=null){
                criteria.andEqualTo("serviceScore",searchMap.get("serviceScore"));
            }
            //物流分数
            if(searchMap.get("expressScore")!=null){
                criteria.andEqualTo("expressScore",searchMap.get("expressScore"));
            }
        }
        return example;
    }

}
